<?php 

declare(strict_types=1);
/**
 * 
 */
namespace WanZ\App\User\Logic;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use WanZ\App\User\Contract\UserBlackContract;
use WanZ\App\Utils\ClientUserCache;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * 用户黑名单管理.
 *
 * Class UserBlackLogic
 */
class UserBlackLogic
{
    use ClientUserCache;

    /**
     * @Inject
     * @var UserBlackContract
     */
    protected $userBlackService;

    /**
     * 移除黑名单
     *
     * @param int $id
     * @return int
     * @throws CommonException
     */
    public function deleteBlack(int $id): int
    {
        $userPhone = $this->userBlackService->getUserById($id, ['user_phone']);
        if (!empty($userPhone)) {
            list($key, $_) = $this->getUserBlackCacheKey($userPhone['userPhone']);
            $this->delOneData($key);
        }

        return $this->userBlackService->deleteUser($id);
    }

    /**
     * 是否存在黑名单里
     *
     * @param string $userPhone
     * @return array
     * @throws CommonException
     */
    public function checkIsBlackByUserPhone(string $userPhone = ''): array
    {
        $default = [false, false];
        if (empty($userPhone)) {
            return $default;
        }

        list($key, $expire) = $this->getUserBlackCacheKey($userPhone);

        $res = $this->getData($key);
        if (!empty($res)) {
            return $res;
        }

        $res = $this->userBlackService->getUsersByUserPhone($userPhone, ['limit_type']);
        if (empty($res)) {
            $this->setData($key, $default, (int)$expire);
            return $default;
        }

        if (count($res) > 1) {
            $default = [true, true];
            $this->setData($key, $default, (int)$expire);
            return $default;
        }

        switch ((int)$res[0]['limitType']) {
            case 1:    //限制充电
                $default = [true, false];
                break;
            case 2:   //限制查看功率曲线图
                $default = [false, true];
                break;
            default:
                break;
        }

        $this->setData($key, $default, (int)$expire);
        return $default;
    }

    /**
     * @param $phone
     * @return array
     */
    public function  getUserBlackCacheKey($phone): array
    {
       $userKey = config('redis.wz_user');
       return [$userKey['getUserBlackKey'].$phone, $userKey['expire']];
    }
}
